package blue.web.dao.service;

import blue.tools.constants.BlueContants;
import blue.commons.enums.StatusEnum;
import blue.dao.base.BaseMapper;
import blue.erp.model.BlueCourse;
import blue.erp.model.SysUser;
import blue.splitclass.dao.ElectiveTaskMapper;
import blue.splitclass.model.ElectiveStudentSelected;
import blue.splitclass.model.ElectiveTask;
import blue.splitclass.model.ElectiveTaskExample;
import blue.tools.commons.BlueStringUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class ElectiveTaskService extends BaseService {

    @Autowired
    private ElectiveTaskMapper electiveTaskMapper;

    @Autowired
    private BlueCourseService blueCourseService;

    @Autowired
    private BlueGradeService blueGradeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ElectiveStudentSelectedService electiveStudentSelectedService;

    public int deleteBatch(String ids, SysUser sysUser) {

        List idList= BlueStringUtils.convertString2Num(ids,",");
        ElectiveTaskExample example=new ElectiveTaskExample();
        example.createCriteria().andIdIn(idList);
        clearCache(sysUser.getSchoolid());
        return this.getBaseMapper().deleteByExample(example);
    }

    //根据任务id创建属于这个任务范围的所有用户的表数据
    public int  createSelectedDbByTask(Long taskId, Long schoolId,Byte type){
        int result=0;
        ElectiveTask task=selectById(taskId,schoolId);
        if(task==null || task.getGradeid()==null){
            return result;
        }
        SysUser selectUser=new SysUser();
        selectUser.setType(type);
        selectUser.setGroupIds(task.getGradeid().toString());
        selectUser.setSchoolid(schoolId);
        List<SysUser> userExtendList=sysUserService.select(selectUser);
        if(CollectionUtils.isNotEmpty(userExtendList)){
            for(SysUser sysUserExtend:userExtendList){
                ElectiveStudentSelected electiveStudentSelected=new ElectiveStudentSelected();
                electiveStudentSelected.setTaskId(taskId);
                electiveStudentSelected.setSchoolid(schoolId);
                electiveStudentSelected.setUserId(sysUserExtend.getId());
                electiveStudentSelected.setUserName(sysUserExtend.getRealName());
                electiveStudentSelected.setStatus((byte) StatusEnum.Init.getValue());
                electiveStudentSelected.setClassId(Long.decode(sysUserExtend.getClassIds()));
                if(electiveStudentSelectedService.save(electiveStudentSelected)>0){
                    result++;
                }
            }
        }

        return result;
    }

    public int save(ElectiveTask record) {

        if(record==null || (StringUtils.isBlank(record.getName()) && record.getId()==null)){
            return 0;
        }

        ElectiveTaskExample example=new ElectiveTaskExample();
        ElectiveTaskExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }else {
            criteria.andNameEqualTo(record.getName()).andIdEqualTo((long) 0);
        }

        clearCache(record.getSchoolid(),record.getId());
        return this.baseSave(record,example);

    }

    public ElectiveTask selectById(Long id, Long schoolId){

        if(id==null || schoolId==null){
            return null;
        }

        Object cacheObject=redisService.getValue(String.format("%s_%s_%s",BlueContants.prefix_elective_taskId,schoolId,id));
        if(cacheObject!=null){
            return JSONObject.parseObject(cacheObject.toString(),ElectiveTask.class);
        }else {
            ElectiveTask record= (ElectiveTask) selectByPrimaryKey(id,schoolId);

            if(record==null){
                return null;
            }

            if(StringUtils.isNotBlank(record.getCourseIds())){

                List<BlueCourse> courseInfos=blueCourseService.selectByIds(record.getCourseIds(),schoolId);

                if(CollectionUtils.isNotEmpty(courseInfos)){
                    record.setList(courseInfos);
                }
            }

            if(record.getGradeid()!=null){
                record.setGradeType(blueGradeService.getTypeByGradeId(record.getGradeid(),schoolId));
            }

            redisService.setValue(String.format("%s_%s_%s",BlueContants.prefix_elective_taskId,schoolId,id),JSONObject.toJSONString(record));

            return record;
        }
    }


    public List<ElectiveTask> selectByObject(ElectiveTask record){

        if(record==null){
            return null;
        }

        ElectiveTaskExample example=new ElectiveTaskExample();
        ElectiveTaskExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }
        if(record.getGradeid()!=null){
            criteria.andGradeidEqualTo(record.getGradeid());
        }

        return this.select(example);
    }


    public int deleteSelectedCourse(Long courseId,Long taskId,Long schoolId){

        if(courseId==null || schoolId==null || schoolId==null){
            return 0;
        }

        ElectiveTask record= (ElectiveTask) selectByPrimaryKey(taskId,schoolId);

        if(record==null){
            return 0;
        }

        if(StringUtils.isNotBlank(record.getCourseIds())) {
            String[] courseids = record.getCourseIds().split(",");
            List courseInfos = new LinkedList();
            for (String course : courseids) {
                if (Long.decode(course) != courseId.longValue()) {
                    courseInfos.add(Long.decode(course));
                }
            }

            record.setCourseIds(StringUtils.join(courseInfos,","));
        }
        clearCache(schoolId,taskId);
        return this.save(record);
    }


    @Override
    public BaseMapper getBaseMapper() {
        return this.electiveTaskMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        if(extend!=null){
            redisService.vagueDelete(String.format("%s_%s_%s",BlueContants.prefix_elective_taskId,schoolId,extend[0]));
        }else {
            redisService.vagueDelete(String.format("%s_%s",BlueContants.prefix_elective_taskId,schoolId));
        }

    }
}
